﻿using Business.CentrifugalPump.Perf;
using Business.NPSH;
using Business.ScrewPump.Perf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Business.Base.DB.DBRules
{
    class DBMappingRules
    {
        public static Dictionary<string, DBMapping> mappingDic;

        private static Dictionary<string, string> getDBFiledMap(Type type)
        {
                       
            Dictionary<string, string> dic = new Dictionary<string, string>();
            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo propertyInfo in properties)
            {
                    DBFieldAttribute dbFieldAttribute = propertyInfo.GetCustomAttribute<DBFieldAttribute>();

                    if (dbFieldAttribute != null)
                    {
                        //Console.WriteLine(dbFieldAttribute.FiledName);
                        dic.Add(dbFieldAttribute.FiledName, propertyInfo.Name);
                        //Console.WriteLine(dbFieldAttribute.FiledName);
                    }

            }
            
            return dic;
        }

        /// <summary>
        /// 根据类型获取该类对应的数据表
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private static String getDBTable(Type type)
        {
            string name = type.Name;
            DBTableAttribute dbTableAttribute= type.GetCustomAttribute<DBTableAttribute>();
            return dbTableAttribute.TableName;
        }

        public static void init()
        {
            mappingDic = new Dictionary<string, DBMapping>();

            Type[] entityTypes = new Type[]
                {  typeof(CentrifugalPumpPerfExperiment),
                   typeof(CentrifugalPumpPerfExperimentRecord),
                   typeof(ScrewPumpPerfExperiment),
                   typeof(ScrewPumpPerfExperimentRecord),
                   typeof(NpshExperiment),
                   typeof(NpshExperimentRecord)

                };
            foreach (Type entityType in entityTypes)
            {
                string entityName = entityType.Name;
                string tableName = getDBTable(entityType);
                mappingDic.Add(entityName, new DBMapping(tableName, getDBFiledMap(entityType)));
            }
        }

        /*static DBMappingRules()
        {           

        }*/
    }
}
